const router = require('koa-router')()
const multer = require('koa-multer')
const fs = require('fs')
const path = require('path')

router.prefix('/upload')

//配置
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        let date = new Date()
        let year = date.getFullYear()
        let month = date.getMonth() + 1
        let day = date.getDate()
        let dir = "./public/uploads/" + year + month + day
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir, {
                recursive: true
            })
        }
        cb(null, dir)
    },
    filename: function (req, file, cb) {
        console.log(file);
        let fileName = file.fieldname + "-" + Date.now() + path.extname(file.originalname)
        cb(null, fileName)
    }
})
//加载配置
const upload = multer({ storage: storage });
// 头像上传
router.post('/img', upload.single('myfile'), async ctx => {
    let path = ctx.req.file.path
    path = ctx.origin + '' + path.replace('public', '')
    console.log('111', path);
    // path = path.replace('\\\\', '\\')
    //返回上传的路经
    ctx.body = {
        data: path
    }
})
// 富文本图片上传
router.post('/editor/img', upload.single('editorFile'), async ctx => {
    let path = ctx.req.file.path
    path = ctx.origin + '' + path.replace('public', '')
    //返回上传的路经
    ctx.body = {
        errno: 0,
        data: [{
            url: path,
            alt: '',
            href: ''
        }]
    }
})

module.exports = router

